package cn.net.xyan.pay.wechat.service

import cn.net.xyan.kotlin.logger
import cn.net.xyan.pay.core.dao.VendorUserInfoDao
import cn.net.xyan.pay.core.entity.PatientUser
import cn.net.xyan.pay.core.entity.VendorUserInfo
import cn.net.xyan.pay.core.service.VendorUserInfoProvider
import me.chanjar.weixin.mp.api.WxMpService
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.context.request.NativeWebRequest

/**
 * Created by zarra on 2017/4/18.
 */

open class WeChatVendorUserInfoProvider:VendorUserInfoProvider{


    @Autowired
    open lateinit var vendorUserInfoDao: VendorUserInfoDao

    @Autowired
    open lateinit var wxMpService: WxMpService

    override fun vendor(): String {
        return "weChat"
    }

    @Transactional
    override fun queryVendorUser(vendorNo: String): VendorUserInfo {
        var vendorUserInfo = vendorUserInfoDao.findByVendorAndVendorNo(vendor(),vendorNo)
        if (vendorUserInfo == null){
            vendorUserInfo = VendorUserInfo(vendor(),vendorNo)
            vendorUserInfo = vendorUserInfoDao.saveAndFlush(vendorUserInfo)
        }

        val wxMpUser = wxMpService.userService.userInfo(vendorNo,"zh_CN")

        vendorUserInfo!!.realName = wxMpUser.nickname
       // vendorUserInfo!!.phone = wxMpUser.
        vendorUserInfo!!.gender = wxMpUser.sex

        vendorUserInfo = vendorUserInfoDao.saveAndFlush(vendorUserInfo)

        logger.info("vendor user:$vendorUserInfo")
        return vendorUserInfo!!

    }

    override fun queryVendorUser(webRequest: NativeWebRequest): VendorUserInfo {
        val code = webRequest.getParameter("code")

        if (code != null){
            val accessToken: WxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code)
            return queryVendorUser(accessToken.openId)
        }

        throw NullPointerException()
    }

}